import { useSnippetsStore } from '@renderer/stores'
import { isInViewport } from '@renderer/utils'
import { useEffect, useRef } from 'react'

export function useAutoScroll () {
  const activeId = useSnippetsStore(s => s.activeId)
  const listRef = useRef<HTMLDivElement | null>(null)

  useEffect(() => {
    if (!listRef.current || !activeId) return

    const activeItem = listRef.current.querySelector('.result-active-item')
    if (!activeItem) return

    if (!isInViewport(activeItem)) {
      activeItem.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
  }, [activeId])

  return {
    listRef,
  }
}
